<template>
	<view class="withdraw-container">
		<!-- 导航栏 -->
		<u-navbar title="转出" left-icon="arrow-left" left-icon-color="#303133" bg-color="#ffffff" fixed placeholder
			@left-click="back" />

		<!-- 主要内容 -->
		<view class="content">
			<!-- 到账方式 -->
			<view class="bank-card-container" @click="showBankSelectPopup = true">
				<view class="bank-card-label">到账银行卡</view>
				<view style="flex:0.7">
					<view class="bank-card-value">
						<text>{{ selectedBank.name || '请选择银行卡' }}</text>
						<u-icon name="arrow-right" size="16" color="#909399" class="right-icon" />
					</view>
					<view class="bank-card-label" style="margin-top: 20rpx;">48小时内到帐</view>
				</view>
			</view>

			<!-- 转出金额 -->
			<view style="background-color: #f5f5f5;">
				<view class="item-container">
					<view class="item-label">转出金额</view>
					<view class="amount-row">
						<view style="height: 29pt;">
							<view class="currency-symbol">¥</view>
						</view>
						<input v-model="withdrawAmount" placeholder="" placeholder-class="input-placeholder"
							border="none" :focus="focusState" class="amount-input" fontSize="28pt"
							type="digit" ref="amountInputRef" id="withdrawAmountInput" />

					</view>
					<view class="available-amount" style="margin-top: 20rpx;">
						<text style="color:#909399;">当前金额{{ availableAmount }}元， </text>
						<text @click="withdrawAll" style="color:#1E88E5;">全部转出</text>
					</view>
					<view class="available-amount" style="color:#909399;">(手续费{{ rate }}%)</view>
				</view>
			</view>

		</view>

		<!-- 转出按钮 -->
		<view class="btn-container">
			<u-button type="primary" :disabled="banks.length === 0" :customStyle="{
				backgroundColor: '#1E88E5',
				color: '#ffffff',
				border: 'none',
				borderRadius: '45rpx',
				height: '90rpx',
				lineHeight: '90rpx',
				fontSize: '32rpx',
			}" @click="handleWithdraw">
				转出
			</u-button>
		</view>

		<!-- 银行卡选择弹出层 -->
		<up-popup :show="showBankSelectPopup" :closeable="true" @close="showBankSelectPopup = false" mode="bottom"
			:round="16">
			<view class="popup-container">
				<view class="popup-title">选择银行卡</view>
				<view class="bank-list">
					<view class="bank-item" v-for="bank in banks" :key="bank.id" @click="selectBank(bank)">
						<view class="bank-info">
							<view class="bank-name">{{ bank.name }}</view>
							<view class="bank-number">{{ bank.number.slice(-4) }}</view>
						</view>
						<u-icon name="checkbox-mark" size="20" color="#1E88E5"
							v-if="selectedBank.name === `${bank.name}(${bank.number.slice(-4)})`" />
					</view>
				</view>
				<button class="cancel-button" @click="showBankSelectPopup = false">取消</button>
			</view>
		</up-popup>

		<!-- 确认转出弹出层 -->
		<up-popup :show="showConfirmPopup" :closeable="true" @close="showConfirmPopup = false" mode="bottom"
			:round="16">
			<view class="confirm-popup-container">
				<view class="confirm-title">转出</view>
				<view class="amount-display">¥{{ withdrawAmount }}</view>
				<view class="confirm-buttons">
					<!-- <button class="btn-cancel" @click="cancelWithdraw">取消</button> -->
					<button class="btn-confirm" @click="confirmWithdraw">确定转出</button>
				</view>
			</view>
		</up-popup>

		<!-- 输入密码弹出层 -->
		<up-popup :show="showPasswordPopup" :closeable="true" @close="showPasswordPopup = false" mode="bottom"
			:round="16">
			<view class="password-popup-container">
				<view class="password-title">输入密码</view>
				<u-input v-model="password" type="password" password-length="6" placeholder="请输入支付密码" border="none"
					class="password-input" />
				<view class="password-footer">
					<text class="forgot-password" style="text-decoration: underline;"
						@click="openSetPasswordPopup">忘记密码？</text>
				</view>
				<view class="no-password">
					没有设置密码？<text class="set-password" style="text-decoration: underline; color: #1E88E5;"
						@click="openSetPasswordPopup">立即设置</text>
				</view>
				<view class="password-buttons">
					<!-- <button class="btn-cancel" @click="cancelPassword">取消</button> -->
					<button class="btn-confirm" @click="submitPassword">确定</button>
				</view>
			</view>
		</up-popup>

		<!-- 手机验证弹出层 -->
		<!-- <up-popup
      :show="showVerifyPopup"
      :closeable="true"
      @close="showVerifyPopup = false"
      mode="bottom"
      :round="16"
    >
      <view class="verify-popup-container">
        <view class="verify-header">
          <u-icon name="arrow-left" size="24" color="#303133" @click="backToPassword" />
          <view class="verify-title">手机验证</view>
        </view>
        <view class="verify-content">
          <view class="verify-message">手机验证码已发送至{{getMaskedNumber(phoneNumber)}}内</view>
          <u-input
            v-model="verifyCode"
            placeholder="请输入验证码"
            border="none"
            class="verify-input"
            type="number"
            maxlength="6"
          />
          <view class="verify-hint">
            <text>10分钟后失效</text>
            <text class="resend-code" @click="resendVerifyCode">重新发送验证码</text>
          </view>
        </view>
        <view class="verify-buttons">
          <button class="btn-confirm" @click="submitVerifyCode">确定</button>
        </view>
      </view>
    </up-popup> -->

		<!-- 设置密码弹出层 -->
		<up-popup :show="showSetPasswordPopup" :closeable="true" @close="showSetPasswordPopup = false" mode="bottom"
			:round="16">
			<view class="set-password-popup-container">
				<view class="set-password-title">设置密码</view>
				<u-input v-model="newPassword" type="password" placeholder="请输入新密码" border="none"
					class="new-password-input" />
				<u-input v-model="confirmPassword" type="password" placeholder="请确认新密码" border="none"
					class="confirm-password-input" />
				<view class="set-password-buttons">
					<button class="btn-confirm" @click="confirmSetPassword">确定</button>
				</view>
			</view>
		</up-popup>
		<phone-popup v-model:show-bind-phone-popup="showVerifyPopup" v-model:phone-number="phoneNumber" />
	</view>
</template>

<script setup>
// 从Vue导入必要的响应式API
import {
	ref, nextTick, getCurrentInstance
} from 'vue';
// 从uni-app导入生命周期钩子
import { onShow } from '@dcloudio/uni-app';
import {
	useRouter
} from 'vue-router';
import {
	navigate as publicNavigate
} from '@/utils/public.js';
import {
	getListByVo
} from '@/api/bankCard';
import {
	getUpdateCode,
	checkPayPwd,
	getInfo
} from '@/api/auth';
import {
	save
} from '@/api/withdraw';
import server from '@/utils/config.js';
import phonePopup from '@/components/phone-popup.vue'
import {
	getById
} from '@/api/sysConfig';



const amountInputRef = ref(null)
let focusState = false
focusState = false;
// 手动点击触发聚焦的函数
const clickFocus = () => {
	try {
		console.log("触发聚焦")
		// 先重置focusState
		focusState = false;
		// 延迟一小段时间后再设置为true，确保重置生效
		setTimeout(() => {
			nextTick(() => {
				focusState = true;
				console.log('focusState设置为true');
				// 使用uni.createSelectorQuery()直接聚焦
				const query = uni.createSelectorQuery();
				query.select('#withdrawAmountInput').fields({
					context: true
				}, (res) => {
					if (res && res.context) {
						try {
							res.context.focus();
							console.log('API直接聚焦成功');
						} catch (e) {
							console.log('API直接聚焦失败:', e);
							// 如果API聚焦失败，尝试使用ref聚焦
							if (amountInputRef.value) {
								try {
									amountInputRef.value.focus();
									console.log('ref聚焦成功');
								} catch (e) {
									console.log('ref聚焦也失败:', e);
								}
							}
						}
					}
				}).exec();
			});
		}, 50); // 50ms延迟，确保重置生效
	} catch (e) {
		console.log('点击聚焦失败:', e);
	}
}

// 自动聚焦实现 - 使用onReady和onShow生命周期钩子
// onReady(async () => {
// 	// onReady表示页面初次渲染完成，可以进行DOM操作
// 	await nextTick();
// 	console.log('页面初次渲染完成，准备尝试自动聚焦');
// 	// 第一次尝试聚焦
// 	await tryAutoFocus();
// });

// 在页面显示时再次尝试聚焦（解决页面切换回来时的聚焦问题）
onShow(async () => {
	await nextTick();
	console.log('页面显示，再次尝试自动聚焦');
	// 延迟200ms后尝试聚焦，确保页面完全显示
	tryAutoFocus();
});

// 封装自动聚焦逻辑，增加重试机制
const tryAutoFocus = async (retryCount = 0) => {
	try {
		// 重置focusState
		focusState = false;
		await nextTick();
		focusState = true;
		
		// 使用uni.createSelectorQuery()尝试直接聚焦
		const query = uni.createSelectorQuery();
		query.select('#withdrawAmountInput').fields({
			context: true
		}, (res) => {
			if (res && res.context) {
				try {
					res.context.focus();
					console.log('自动聚焦成功');
				} catch (e) {
					console.log('自动聚焦尝试失败:', e);
					// 如果失败且重试次数小于3次，则在1秒后重试
					if (retryCount < 3) {
						console.log(`1秒后进行第${retryCount + 2}次聚焦尝试`);
						setTimeout(() => {
							tryAutoFocus(retryCount + 1);
						}, 1000);
					}
				}
			}
		}).exec();
	} catch (e) {
		console.log('自动聚焦逻辑执行异常:', e);
	}
}
// 初始化数据
const withdrawAmount = ref('');
const availableAmount = ref('40.00'); // 可转出金额，实际应从接口获取
const router = useRouter();
const showBankSelectPopup = ref(false);
const showConfirmPopup = ref(false);
const showPasswordPopup = ref(false);
const showVerifyPopup = ref(false);
const showSetPasswordPopup = ref(false);
const password = ref('');
const verifyCode = ref('');
const newPassword = ref('');
const confirmPassword = ref('');
const selectedBank = ref({
	id: 0,
	name: '',
});
const rate = ref('0.00');
const banks = ref([
]);
// 显示的手机号
const phoneNumber = ref('151****0012');
const getMaskedNumber = (phone) => {
	return phone.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
};
const getLastNumber = (number) => {
	return number.slice(-4);
};
// 返回上一层弹出层
const backToPassword = () => {
	showVerifyPopup.value = false;
	showSetPasswordPopup.value = false;
};

// 重新发送验证码
const resendVerifyCode = () => {
	// 这里实现重新发送验证码的逻辑
	uni.showToast({
		title: '验证码已重新发送',
		icon: 'success'
	});
};

// 提交验证码
const submitVerifyCode = () => {
	if (!verifyCode.value) {
		uni.showToast({
			title: '请输入验证码',
			icon: 'none'
		});
		return;
	}

	if (verifyCode.value.length !== 6) {
		uni.showToast({
			title: '验证码必须为6位',
			icon: 'none'
		});
		return;
	}

	// 验证码校验通过，进入设置密码页面
	showVerifyPopup.value = false;
	showSetPasswordPopup.value = true;
};

// 确认设置密码
const confirmSetPassword = () => {
	if (!newPassword.value) {
		uni.showToast({
			title: '请输入新密码',
			icon: 'none'
		});
		return;
	}

	if (newPassword.value.length < 6) {
		uni.showToast({
			title: '密码长度不能少于6位',
			icon: 'none'
		});
		return;
	}

	if (newPassword.value !== confirmPassword.value) {
		uni.showToast({
			title: '两次输入的密码不一致',
			icon: 'none'
		});
		return;
	}

	// 密码设置成功
	showSetPasswordPopup.value = false;
	uni.showToast({
		title: '密码设置成功',
		icon: 'success'
	});

	// 重置表单
	newPassword.value = '';
	confirmPassword.value = '';
	verifyCode.value = '';
};

// 确认转出
const confirmWithdraw = () => {
	showConfirmPopup.value = false;
	showPasswordPopup.value = true;
};

// 取消转出
const cancelWithdraw = () => {
	showConfirmPopup.value = false;
};

// 提交密码
const submitPassword = async () => {
	if (!password.value) {
		uni.showToast({
			title: '请输入支付密码',
			icon: 'none'
		});
		return;
	}
	// 密码校验逻辑
	if (password.value.length !== 6) {
		uni.showToast({
			title: '支付密码必须为6位',
			icon: 'none'
		});
		return;
	}
	const res = await checkPayPwd(password.value).catch(e => {
		console.log(e);
		uni.showToast({
			title: '支付失败，请稍后再尝试',
			icon: 'none'
		});
	});
	if (res.code === 200) {
		// 密码正确，执行转出
		showPasswordPopup.value = false;
		let tmp = JSON.parse(uni.getStorageSync('userInfo'))
		let nextAmount = parseFloat(availableAmount.value) - parseFloat(withdrawAmount.value);
		let paramData = {
			amount: withdrawAmount.value,
			nextAmount: nextAmount,
			bankCardId: selectedBank.value.id,
			employeeId: tmp.info.id,
			corpId: tmp.info.corpId
		}
		const res2 = await save(paramData).catch(e => {
			console.log(e);
			uni.showToast({
				title: '转出失败，请稍后再尝试',
				icon: 'none'
			});
		});
		if (res2.code === 200) {
			// 转出成功
			uni.redirectTo({
				url: '/pages/my/withdraw/success'
			});
			// 重置表单
			password.value = '';
			withdrawAmount.value = '';
		} else {
			console.log(res2);
			uni.showToast({
				title: '转出失败',
				icon: 'none'
			});
		}
	} else if (res.code === 300) {
		uni.showToast({
			title: '支付密码错误',
			icon: 'none'
		});
	} else {
		console.log(res)
		uni.showToast({
			title: '支付失败',
			icon: 'none'
		});
	}

	// 可跳转到转出记录页面
	// router.push('/pages/my/withdraw/record');
};

// 取消输入密码
const cancelPassword = () => {
	showPasswordPopup.value = false;
	password.value = '';
};

// 跳转到设置密码页面
const navigateToSetPassword = () => {
	showPasswordPopup.value = false;
	// 这里假设设置密码的页面路径是/pages/my/setting/password
	router.push('/pages/my/setting/password');
};

// 返回上一页
const back = () => {
	publicNavigate('back');
};

// 处理转出
const handleWithdraw = () => {
	if (!withdrawAmount.value) {
		uni.showToast({
			title: '请输入转出金额',
			icon: 'none'
		});
		return;
	}

	if (Number(withdrawAmount.value) <= 0) {
		uni.showToast({
			title: '转出金额必须大于0',
			icon: 'none'
		});
		return;
	}

	if (Number(withdrawAmount.value) > Number(availableAmount.value)) {
		uni.showToast({
			title: '转出金额不能超过可转出金额',
			icon: 'none'
		});
		return;
	}

	// 校验通过，显示确认转出弹出层
	showConfirmPopup.value = true;
};
const withdrawAll = () => {
	withdrawAmount.value = availableAmount.value;
}
const getAllBankCards = async () => {

	let tmp = JSON.parse(uni.getStorageSync('userInfo'));
	// 获取银行卡列表
	const res = await getListByVo({
		employeeId: tmp.info.id
	}).catch((err) => {
		console.log(err);
		uni.showToast({
			title: '获取银行卡列表失败',
			icon: 'none'
		});
	});
	if (res.code == 200) {
		banks.value = [...res.data.list]
		if (res.data.list.length > 0) {
			selectedBank.value.name = `${res.data.list[0].name}(${res.data.list[0].number.slice(-4)})`;
			selectedBank.value.id = res.data.list[0].id;
		}
	} else {
		console.log(res)
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
	}
}
const getAmount = () => {
	let tmp = JSON.parse(uni.getStorageSync('userInfo'));
	availableAmount.value = tmp.amount;
}
// getAmount()
getAllBankCards()
// 选择银行卡
const selectBank = (bank) => {
	selectedBank.value.name = `${bank.name}(${bank.number.slice(-4)})`;
	selectedBank.value.id = bank.id;
	showBankSelectPopup.value = false;
};
const userInfo = ref({})
const flushInfo = () => {
	getInfo().then(res => {
		if (res.code == 200) {
			// console.log(res.data)
			availableAmount.value = res.data.amount;
			uni.setStorageSync('userInfo', JSON.stringify(res.data));
			// console.log("userInfo", uni.getStorageSync('userInfo'));
			userInfo.value = res.data.info
			phoneNumber.value = res.data.info.phone
		}
	})
	getById(2).then(res => {
		if (res.code == 200) {
			rate.value = parseFloat(res.data.vo.value)
		} else {
			uni.showToast({
				title: '加载失败',
				icon: 'none'
			});
			console.error(res)
		}
	}).catch(err => {
		console.err(err)
		uni.showToast({
			title: '加载失败',
			icon: 'none'
		});
	})
}
flushInfo()

// 打开设置密码弹窗 - 先验证手机
const openSetPasswordPopup = async () => {
	// showBindPhonePopup.value = true;
	const res = await getUpdateCode(phoneNumber.value).catch(error => {
		uni.showToast({
			title: '获取验证码失败',
			icon: 'none'
		});
		console.log(error)
	});
	if (res.code === 200) {
		// 先打开手机验证弹窗
		showVerifyPopup.value = true;

	} else {
		console.log(res)
		uni.showToast({
			title: res.msg,
			icon: 'none'
		});
	}
};
</script>

<style scoped>
.withdraw-container {
	display: flex;
	flex-direction: column;
	min-height: 100vh;
	background-color: #ffffff;

}

.content {
	flex: 1;
	/* padding: 30rpx; */

}

.bank-card-container {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 60rpx;
	background-color: #f5f5f5;
}

.bank-card-label {
	font-size: 28rpx;
	color: #909399;
}

.bank-card-value {
	display: flex;
	justify-content: space-between;
	align-items: center;
	font-size: 32rpx;
	color: #303133;
}

.bank-card-value text {
	font-weight: bold;
}

.right-icon {
	margin-left: 10rpx;
}

.item-container {
	/* margin-bottom: 30rpx; */
	background-color: #ffffff;
	border-top-right-radius: 40rpx;
	border-top-left-radius: 40rpx;
	padding: 60rpx;
	margin-bottom: 20rpx;
}

/* 确认转出弹出层样式 */
.confirm-popup-container {
	padding: 40rpx;
	text-align: center;
	height: 500rpx;
	box-sizing: border-box;
}

.confirm-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
}

.amount-display {
	font-size: 60rpx;
	color: #303133;
	margin-bottom: 60rpx;
}

.confirm-buttons {
	display: flex;
	justify-content: space-between;
}

/* 输入密码弹出层样式 */
.password-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.password-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
	text-align: center;
}

.password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 30rpx;
}

.password-footer {
	display: flex;
	justify-content: flex-end;
	margin-bottom: 40rpx;
}

.forgot-password {
	font-size: 28rpx;
	color: #1E88E5;
	cursor: pointer;
}

.password-buttons {
	display: flex;
	justify-content: space-between;
	margin-top: 30rpx;
}

/* 手机验证弹出层样式 */
.verify-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.verify-header {
	display: flex;
	align-items: center;
	margin-bottom: 40rpx;
}

.verify-title {
	font-size: 36rpx;
	color: #303133;
	margin-left: 50%;
	transform: translateX(-50%);
}

.verify-content {
	margin-bottom: 40rpx;
}

.verify-message {
	font-size: 28rpx;
	color: #303133;
	margin-bottom: 30rpx;
}

.verify-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 20rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.verify-hint {
	display: flex;
	justify-content: space-between;
	font-size: 24rpx;
	color: #909399;
}

.resend-code {
	color: #1E88E5;
}

.verify-buttons {
	margin-top: 40rpx;
}

/* 设置密码弹出层样式 */
.set-password-popup-container {
	padding: 40rpx;
	height: 500rpx;
	box-sizing: border-box;
}

.set-password-title {
	font-size: 36rpx;
	color: #303133;
	margin-bottom: 40rpx;
	text-align: center;
}

.new-password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 30rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.confirm-password-input {
	font-size: 36rpx;
	text-align: center;
	letter-spacing: 10rpx;
	margin-bottom: 40rpx;
	border-bottom: 1rpx solid #f0f0f0;
	padding-bottom: 10rpx;
}

.set-password-buttons {
	margin-top: 20rpx;
}

/* 没有设置密码提示样式 */
.no-password {
	font-size: 28rpx;
	color: #909399;
	text-align: center;
	margin-top: 20rpx;
	margin-bottom: 30rpx;
}

.set-password {
	font-size: 28rpx;
	color: #1E88E5;
}

/* 按钮样式 */
.btn-cancel {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	background-color: #f5f5f5;
	color: #303133;
	border-radius: 45rpx;
	margin-right: 20rpx;
}

.btn-confirm {
	flex: 1;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	background-color: #1E88E5;
	color: #ffffff;
	border-radius: 45rpx;
	margin-left: 20rpx;
}

.item-label {
	line-height: 15pt;
	color: rgba(0, 0, 0, 1);
	font-size: 12pt;
	font-weight: bold;
	text-align: left;
	margin-bottom: 20px;
}

.amount-row {
	display: flex;
	align-items: center;
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	position: relative;
	padding-bottom: 20px;
	border-bottom: 4rpx solid #f0f0f0;
}

.currency-symbol {
	/* line-height: 39pt; */
	color: rgba(0, 0, 0, 1);
	font-size: 21pt;
	font-weight: bold;
	text-align: left;
	line-height: 21pt;
}

.amount-input {
	line-height: 29pt !important;
	height: 29pt !important;
	color: #000;
	font-size: 28pt;
	text-align: left;
	padding-left: 18rpx;
	font-weight: bold;
	flex: 1;
}

.input-placeholder {
	color: rgba(187, 187, 187, 1);
	font-size: 28rpx;
}

.available-amount {
	line-height: 17pt;
	color: rgba(0, 0, 0, 1);
	font-size: 12pt;
	text-align: left;
	white-space: nowrap;
}

.btn-container {
	padding: 30rpx;
	position: fixed;
	bottom: 0;
	left: 0;
	width: 100%;
	box-sizing: border-box;
	background-color: #ffffff;
	border-radius: 1px;
}

/* 弹出层样式 */
.popup-container {
	padding: 30rpx;
}

.popup-title {
	font-size: 32rpx;
	font-weight: bold;
	text-align: center;
	margin-bottom: 30rpx;
}

.bank-list {
	max-height: 500rpx;
	overflow-y: auto;
}

.bank-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f0f0;
}

.bank-info {
	flex: 1;
}

.bank-name {
	font-size: 30rpx;
	color: #303133;
}

.bank-number {
	font-size: 26rpx;
	color: #909399;
}

.cancel-button {
	width: 100%;
	height: 90rpx;
	line-height: 90rpx;
	text-align: center;
	font-size: 32rpx;
	color: #303133;
	background-color: #f5f5f5;
	border-radius: 45rpx;
	margin-top: 30rpx;
}
</style>